/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radiostation;

import java.awt.Color;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import model.Album;
import model.Song;

/**
 *
 * @author stamatelopoulos
 */
public class ListMusicGroupAlbumForm extends javax.swing.JFrame {

    /**
     * Creates new form ListMusicGroupForm
     */
    EntityManager em;
    int selectedRow;
    Album album;
   
    public ListMusicGroupAlbumForm() {
        em = DBManager.em;
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        initComponents();
        manageButtons();
        DBManager.centerOnScreen(this);
        this.MusicgroupAlbumTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                
        TableCellRenderer rendererFromHeader = MusicgroupAlbumTable.getTableHeader().getDefaultRenderer();
        JLabel Id = (JLabel)rendererFromHeader;
        Id.setHorizontalAlignment(JLabel.CENTER);

        JTableHeader header = MusicgroupAlbumTable.getTableHeader();
        header.setForeground(Color.red);

        DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
        centerRenderer.setHorizontalAlignment(JLabel.CENTER);
        MusicgroupAlbumTable.getColumnModel().getColumn(0).setCellRenderer(centerRenderer);
        MusicgroupAlbumTable.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
        MusicgroupAlbumTable.getColumnModel().getColumn(2).setCellRenderer(new DateCellRenderer());
        MusicgroupAlbumTable.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
        MusicgroupAlbumTable.getColumnModel().getColumn(4).setCellRenderer(centerRenderer);
    }

        private void manageButtons() {
        selectedRow = MusicgroupAlbumTable.getSelectedRow();
        editButton.setEnabled(selectedRow >= 0);
        delButton.setEnabled(selectedRow >= 0);

        if (selectedRow >= 0) {
            album = MusicGroupAlbumList.get(MusicgroupAlbumTable.convertRowIndexToModel(selectedRow));
        }
        }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        MusicGroupAlbumQuery = java.beans.Beans.isDesignTime() ? null : em.createQuery("select a from Album a where a.fgroupId is not null order by a.title");
        MusicGroupAlbumList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(MusicGroupAlbumQuery.getResultList());
        jScrollPane1 = new javax.swing.JScrollPane();
        MusicgroupAlbumTable = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        insButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        delButton = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Πίνακας Άλμπουμ Συγκροτημάτων");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, MusicGroupAlbumList, MusicgroupAlbumTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(Long.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${title}"));
        columnBinding.setColumnName("Τίτλος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${releasedate}"));
        columnBinding.setColumnName("Ημερ.Κυκλοφορίας");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${type}"));
        columnBinding.setColumnName("Τύπος");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${disknumber}"));
        columnBinding.setColumnName("Αρ.Δίσκων");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${fgroupId.name}"));
        columnBinding.setColumnName("Συγκρότημα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${flabelId.name}"));
        columnBinding.setColumnName("Εταιρία Παραγωγής");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        MusicgroupAlbumTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                MusicgroupAlbumTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(MusicgroupAlbumTable);
        if (MusicgroupAlbumTable.getColumnModel().getColumnCount() > 0) {
            MusicgroupAlbumTable.getColumnModel().getColumn(0).setMaxWidth(70);
            MusicgroupAlbumTable.getColumnModel().getColumn(1).setMaxWidth(250);
            MusicgroupAlbumTable.getColumnModel().getColumn(2).setMaxWidth(170);
            MusicgroupAlbumTable.getColumnModel().getColumn(3).setMaxWidth(70);
            MusicgroupAlbumTable.getColumnModel().getColumn(4).setMaxWidth(80);
            MusicgroupAlbumTable.getColumnModel().getColumn(5).setMaxWidth(150);
            MusicgroupAlbumTable.getColumnModel().getColumn(6).setMaxWidth(150);
        }

        jLabel1.setForeground(new java.awt.Color(0, 51, 255));
        jLabel1.setText("Άλμπουμ Συγκροτημάτων:");

        insButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.gif"))); // NOI18N
        insButton.setText("Εισαγωγή");
        insButton.setToolTipText("Πατήστε για Εισαγωγή νέου Συγκροτήματος");
        insButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                insButtonActionPerformed(evt);
            }
        });

        editButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/edit.png"))); // NOI18N
        editButton.setText("Επεξεργασία");
        editButton.setToolTipText("Πατήστε για Επεξεργασία υπάρχοντος Συγκροτήματος ");
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        delButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.gif"))); // NOI18N
        delButton.setText("Διαγραφή");
        delButton.setToolTipText("Πατήστε για Διαγραφή υπάρχοντος Συγκροτήματος");
        delButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delButtonActionPerformed(evt);
            }
        });

        exitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/stock_exit.png"))); // NOI18N
        exitButton.setText("Έξοδος");
        exitButton.setToolTipText("Πατήστε για επιστροφή στο Κεντρικό Μενού");
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 899, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addComponent(insButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(editButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(delButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(exitButton)
                .addGap(48, 48, 48))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(insButton)
                    .addComponent(editButton)
                    .addComponent(delButton)
                    .addComponent(exitButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void insButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insButtonActionPerformed

        Album alb = new Album();
        em.persist(alb);
        EditMusicGroupAlbumForm emgaf = new EditMusicGroupAlbumForm(alb, false);
        emgaf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);
        
        emgaf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    manageButtons();
                    em.persist(alb);
                    MusicGroupAlbumList.add(alb);                   
                    em.getTransaction().commit();
                    java.util.Collection data = MusicGroupAlbumQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);  
                    }
                    MusicGroupAlbumList.clear();
                    MusicGroupAlbumList.addAll(data);

                    int row = MusicGroupAlbumList.size() - 1;
                    MusicgroupAlbumTable.setRowSelectionInterval(row, row);
                    MusicgroupAlbumTable.scrollRectToVisible(MusicgroupAlbumTable.getCellRect(row, 0, true));
                    thisFrame.setEnabled(true);
                }
                else {
                   thisFrame.setEnabled(true);
                   em.getTransaction().rollback();
                   em.getTransaction().begin();
                   java.util.Collection data = MusicGroupAlbumQuery.getResultList();
                   for (Object entity : data) {
                       em.refresh(entity);  
                   }
                   MusicGroupAlbumList.clear();
                   MusicGroupAlbumList.addAll(data);
                   manageButtons();
                }
                    MusicgroupAlbumTable.repaint();
        }

            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });
    }//GEN-LAST:event_insButtonActionPerformed

    private void closeMe(boolean exitAndSave) {
        MyWindowEvent we = new MyWindowEvent(this, WindowEvent.WINDOW_CLOSED, exitAndSave);
        for (WindowListener l : this.getWindowListeners()) {
            l.windowClosed(we);
        }
        this.setVisible(false);
    }
    
    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitButtonActionPerformed
        // TODO add your handling code here:
        closeMe(true);
    }//GEN-LAST:event_exitButtonActionPerformed

    private void delButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delButtonActionPerformed
        // TODO add your handling code here:
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        selectedRow = MusicgroupAlbumTable.getSelectedRow();
        album = MusicGroupAlbumList.get(MusicgroupAlbumTable.convertRowIndexToModel(selectedRow));
        
        if (selectedRow>=0){
            int c = JOptionPane.showConfirmDialog(null, "Επιθυμείτε σίγουρα να διαγράψετε το Άλμουμ " + album.getTitle() + "?", "Διαγραφή Συγκροτήματος",JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (c == 0){ 
                Album al = MusicGroupAlbumList.get(MusicgroupAlbumTable.convertRowIndexToModel(selectedRow));
                
                for (Song song : al.getSongList()){
                    song.setFalbumId(null);
                }    

                MusicGroupAlbumList.remove(al);
                em.remove(al);
                em.getTransaction().commit(); 
                JOptionPane.showMessageDialog(null, "Η Διαγραφή του Άλμπουμ έγινε με επιτυχία!", "ΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);
            }
            manageButtons();
        }
        else{
            JOptionPane.showMessageDialog(null, "Δεν έχετε επιλέξει Άλμπουμ για Διαγραφή.", "ΑΝΕΠΙΤΥΧΗΣ ΔΙΑΓΡΑΦΗ", JOptionPane.INFORMATION_MESSAGE);        
        }
    }//GEN-LAST:event_delButtonActionPerformed

    private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
        // TODO add your handling code here:
        selectedRow = MusicgroupAlbumTable.getSelectedRow();
        alb = MusicGroupAlbumList.get(MusicgroupAlbumTable.convertRowIndexToModel(selectedRow));
        
        EditMusicGroupAlbumForm emgaf = new EditMusicGroupAlbumForm(alb, true);
        emgaf.setVisible(true);
        thisFrame = this;
        thisFrame.setEnabled(false);

        emgaf.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Window close event occur");
                if (((MyWindowEvent)arg0).exitAndSave) {
                    em.persist(alb);
                    MusicGroupAlbumList.set(selectedRow,alb);
                    em.getTransaction().commit(); 
                    thisFrame.setEnabled(true);
                    java.util.Collection data = MusicGroupAlbumQuery.getResultList();
                    for (Object entity : data) {
                        em.refresh(entity);  
                    }
                    MusicGroupAlbumList.clear();
                    MusicGroupAlbumList.addAll(data);
                }
                else {
                   thisFrame.setEnabled(true);
                   em.getTransaction().rollback();
                   em.getTransaction().begin();
                   java.util.Collection data = MusicGroupAlbumQuery.getResultList();
                   for (Object entity : data) {
                       em.refresh(entity);  
                   }
                   MusicGroupAlbumList.clear();
                   MusicGroupAlbumList.addAll(data);
                   manageButtons();
            }
        }  
            public void windowActivated(WindowEvent arg0) {

                System.out.println("Window Activated");
            }

            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }

            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }

            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }

            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }

            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened2");

            }
        });
    }//GEN-LAST:event_editButtonActionPerformed

    private void MusicgroupAlbumTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MusicgroupAlbumTableMouseClicked
        // TODO add your handling code here:
        manageButtons();
    }//GEN-LAST:event_MusicgroupAlbumTableMouseClicked
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<model.Album> MusicGroupAlbumList;
    private javax.persistence.Query MusicGroupAlbumQuery;
    private javax.swing.JTable MusicgroupAlbumTable;
    private javax.swing.JButton delButton;
    private javax.swing.JButton editButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JButton insButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    JFrame thisFrame;
    Album alb;
}
